<template>
  <div ref="potreeContainer" id="potree-container" style="width:100%;height:600px;"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted,watch } from 'vue';
const props = defineProps(['fileUrl']);
const potreeContainer = ref(null);

const renderPotree = () => {
  if (!props.fileUrl) return;
  loadPotreeLibs().then(() => {

    const viewer = new window.Potree.Viewer(potreeContainer.value);
    viewer.setEDLEnabled(true);
    viewer.setFOV(60);
    viewer.setPointBudget(1_000_000);

    // 检查多种API调用方式
    if (window.Potree && window.Potree.loadPointCloud) {
      window.Potree.loadPointCloud(props.fileUrl, '点云', (e) => {
        viewer.scene.addPointCloud(e.pointcloud);
        viewer.fitToScreen();
      });
    } else if (viewer.loadPointCloud) {
      viewer.loadPointCloud(props.fileUrl, '点云', (e) => {
        viewer.scene.addPointCloud(e.pointcloud);
        viewer.fitToScreen();
      });
    } else {
      console.error('❌ 无法找到 loadPointCloud 方法');
      console.log('viewer methods:', Object.keys(viewer));
    }
  });
};

watch(() => props.fileUrl, renderPotree);
onMounted(renderPotree);

function loadPotreeLibs() {
  if (!window.Potree) {
    return Promise.all([
      loadScript('/potree/potree.js'),
      loadScript('/libs/proj4/proj4.js'),
      loadScript('/libs/jquery/jquery-3.1.1.min.js'),
      loadScript('/libs/other/BinaryHeap.js'),
      loadScript('/libs/tween/tween.min.js'),
      loadScript('/libs/plasio/js/laslaz.js'),
      loadScript('/libs/spectrum/spectrum.js'),
      loadScript('/libs/d3/d3.js'),
      loadScript('libs/openlayers3/ol.js'),
      loadScript('/libs/i18next/i18next.js'),
      loadCss('/potree/potree.css')
    ]);
  }
  return Promise.resolve();
}
function loadScript(src) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = src;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}
function loadCss(href) {
  return new Promise((resolve) => {
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = href;
    link.onload = resolve;
    document.head.appendChild(link);
  });
}

</script>
